package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/getuserbyaid")
public class GetUserByAId extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
        String msg="未知错误";
        UserInfo userInfo=new UserInfo();
        //1.得到参数并效验
        String aidStr=req.getParameter("aid");
        if (!StrUtil.isBlank(aidStr)){
            int aid=Integer.valueOf(aidStr);
            if (aid>0){
                //2.查询数据库，并组织返回
                Connection connection=DBUtils.getConnection();
                String sql="select * from userinfo where uid=(select uid from article where aid=?)";
                PreparedStatement statement=connection.prepareStatement(sql);
                statement.setInt(1,aid);
                ResultSet resultSet=statement.executeQuery();
                if (resultSet.next()){
                    userInfo.setUid(resultSet.getInt("uid"));
                    userInfo.setUsername(resultSet.getString("username"));
                    userInfo.setImg(resultSet.getString("img"));
                }
                //查询用户发表所有文章数
                sql= "select count(*) as acount from article where uid=(select uid from article where aid=?)";
                PreparedStatement statement2=connection.prepareStatement(sql);
                statement2.setInt(1,aid);
                ResultSet resultSet2=statement2.executeQuery();
                if (resultSet2.next()){
                    userInfo.setAcount(resultSet2.getInt("acount"));
                }
                msg="";
                //关闭
                DBUtils.close(resultSet2,statement2,null);
                DBUtils.close(resultSet,statement,connection);
            }else {
                msg="非法错误！";
            }
        }else {
            msg="非法参数！";
        }
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,userInfo,msg)));
    }
}
